package com.zrm.zfcrpa.configuration.security;

import com.alibaba.fastjson.JSONObject;
import com.zrm.zfcrpa.applicationListener.LoginEvent;
import com.zrm.zfcrpa.dao.mapper.loginMapper.LoginDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class MyUserDetals implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private LoginDao loginDao;

    @Override
    public UserDetails loadUserByUsername(String s) {
        JSONObject object = loginDao.doLogin(s);
        if (object != null) {
            login_info(s,"pc登录");
            return new User(object.get("zrmUserName").toString(), object.getString("zrmPassword").toString(), Arrays.asList(new SimpleGrantedAuthority(object.get("zrmTranslateDescr").toString().trim())));
        } else {
            throw new UsernameNotFoundException("用户名没找到");
        }
    }

    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
       /* String userAccount = loginDao.isUser(mobile);
        if(StringUtils.isBlank(userAccount)){
            loginDao.addMobileUser();
        }*/
        return new User(mobile, bCryptPasswordEncoder.encode("1234"), Arrays.asList(new SimpleGrantedAuthority("企业用户")));
    }

    public void login_info(String userName,String type) {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Map<String, String> map = new HashMap<>();
        map.put("ip", request.getRemoteAddr());
        map.put("userName", userName);
        map.put("loginType",type);
        applicationEventPublisher.publishEvent(new LoginEvent(map));
    }
}
